w3resource

Read data from a CSV file into a Pandas DataFrame and convert to NumPy array

NumPy: I/O Operations Exercise-15 with Solution

Write a NumPy program that reads data from a CSV file into a Pandas DataFrame and then converts it to a NumPy array.

Sample Solution:

Python Code:

import pandas as pd
import numpy as np

# Define the path to the CSV file
csv_file_path = 'data.csv'

# Read the CSV file into a Pandas DataFrame
df = pd.read_csv(csv_file_path)

# Convert the DataFrame to a NumPy array
data_array = df.to_numpy()

# Print the DataFrame and the NumPy array
print("Pandas DataFrame:")
print(df)

print("\nNumPy Array:")
print(data_array)

Output:

Pandas DataFrame:
   10  Shaun Hephzibah  95
0  11  Zayden Jeremiah  90
1  12    Luna Marciano  85
2  13     Kord Shanene  96
3  14     Coeus Zorana  95

NumPy Array:
[[11 'Zayden Jeremiah' 90]
 [12 'Luna Marciano' 85]
 [13 'Kord Shanene' 96]
 [14 'Coeus Zorana' 95]]

Explanation:

  • Import Pandas and NumPy Libraries: Import the Pandas and NumPy libraries to handle DataFrames and arrays.
  • Define CSV File Path: Specify the path to the CSV file containing the data.
  • Read CSV File into DataFrame: Use pd.read_csv() to read the contents of the CSV file into a Pandas DataFrame.
  • Convert DataFrame to NumPy Array: Use the to_numpy() method of the DataFrame to convert it into a NumPy array.
  • Print DataFrame and NumPy Array: Output both the DataFrame and the resulting NumPy array to verify the data has been read and converted correctly.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: How to write a NumPy array with numeric data to a JSON file?
Next: How to write a NumPy array to a SQLite database and read it back?.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.